$(function() {
    // 初始化日期选择器
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        todayBtn: 'linked',
        language: 'zh-CN',
        todayHighlight: true
    });
    
    // 设置默认日期范围（最近7天）
    var today = new Date();
    var lastWeek = new Date();
    lastWeek.setDate(today.getDate() - 7);
    
    $('#startDateInput').datepicker('setDate', lastWeek);
    $('#endDateInput').datepicker('setDate', today);
    
    // 初始化数据表格
    var historyTable = $('#historyTable').DataTable({
        responsive: true,
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel'
        ],
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            }
        },
        order: [[8, 'desc']], // 默认按记录时间降序排序
        columns: [
            { data: 'monitorId' },
            { data: 'warehouseName' },
            { data: 'storageArea' },
            { data: 'deviceId' },
            { data: 'temperature' },
            { data: 'humidity' },
            { 
                data: 'status',
                render: function(data) {
                    if (data === '0') {
                        return '<span class="status-normal"><i class="fa fa-check-circle"></i> 正常</span>';
                    } else if (data === '1') {
                        return '<span class="status-warning"><i class="fa fa-exclamation-circle"></i> 温度异常</span>';
                    } else if (data === '2') {
                        return '<span class="status-warning"><i class="fa fa-exclamation-circle"></i> 湿度异常</span>';
                    } else {
                        return '<span class="status-danger"><i class="fa fa-times-circle"></i> 温湿度均异常</span>';
                    }
                }
            },
            { data: 'alarmInfo' },
            { 
                data: 'recordTime',
                render: function(data) {
                    return formatDateTime(data);
                }
            },
            { 
                data: 'processStatus',
                render: function(data) {
                    if (data === '0') {
                        return '<span class="badge badge-danger">未处理</span>';
                    } else {
                        return '<span class="badge badge-success">已处理</span>';
                    }
                }
            }
        ]
    });
    
    // 加载仓库下拉框选项
    loadWarehouseOptions();
    
    // 仓库选择变更事件
    $('#warehouseSelect').on('change', function() {
        var warehouseId = $(this).val();
        if (warehouseId) {
            loadStorageAreas(warehouseId);
        } else {
            $('#storageAreaSelect').html('<option value="">全部区域</option>');
            $('#deviceIdSelect').html('<option value="">全部设备</option>');
        }
    });
    
    // 区域选择变更事件
    $('#storageAreaSelect').on('change', function() {
        var warehouseId = $('#warehouseSelect').val();
        var storageArea = $(this).val();
        if (warehouseId && storageArea) {
            loadDeviceIds(warehouseId, storageArea);
        } else {
            $('#deviceIdSelect').html('<option value="">全部设备</option>');
        }
    });
    
    // 查询按钮点击事件
    $('#searchBtn').on('click', function() {
        searchHistoryData();
    });
    
    // 重置按钮点击事件
    $('#resetBtn').on('click', function() {
        $('#storageAreaSelect').html('<option value="">全部区域</option>');
        $('#deviceIdSelect').html('<option value="">全部设备</option>');
        
        // 重置日期为最近7天
        var today = new Date();
        var lastWeek = new Date();
        lastWeek.setDate(today.getDate() - 7);
        
        $('#startDateInput').datepicker('setDate', lastWeek);
        $('#endDateInput').datepicker('setDate', today);
        
        // 清空表格
        historyTable.clear().draw();
    });
    
    // 加载仓库选项
    function loadWarehouseOptions() {
        $.ajax({
            url: '/warehouse/list',
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var options = '';
                    $.each(res.data, function(index, warehouse) {
                        options += '<option value="' + warehouse.warehouseId + '">' + warehouse.warehouseName + '</option>';
                    });
                    $('#warehouseSelect').append(options);
                    
                    // 如果有仓库，默认选中第一个并加载区域
                    if (res.data && res.data.length > 0) {
                        $('#warehouseSelect').val(res.data[0].warehouseId).trigger('change');
                    }
                }
            }
        });
    }
    
    // 加载区域选项
    function loadStorageAreas(warehouseId) {
        $.ajax({
            url: '/warehouse/coldStorageMonitor/latest/' + warehouseId,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var areas = [];
                    var options = '<option value="">全部区域</option>';
                    
                    // 提取不重复的区域
                    $.each(res.data, function(index, monitor) {
                        if (monitor.storageArea && !areas.includes(monitor.storageArea)) {
                            areas.push(monitor.storageArea);
                            options += '<option value="' + monitor.storageArea + '">' + monitor.storageArea + '</option>';
                        }
                    });
                    
                    $('#storageAreaSelect').html(options);
                }
            }
        });
    }
    
    // 加载设备ID选项
    function loadDeviceIds(warehouseId, storageArea) {
        $.ajax({
            url: '/warehouse/coldStorageMonitor/latest/' + warehouseId,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var deviceIds = [];
                    var options = '<option value="">全部设备</option>';
                    
                    // 提取不重复的设备ID
                    $.each(res.data, function(index, monitor) {
                        if (monitor.storageArea === storageArea && monitor.deviceId && !deviceIds.includes(monitor.deviceId)) {
                            deviceIds.push(monitor.deviceId);
                            options += '<option value="' + monitor.deviceId + '">' + monitor.deviceId + '</option>';
                        }
                    });
                    
                    $('#deviceIdSelect').html(options);
                }
            }
        });
    }
    
    // 查询历史数据
    function searchHistoryData() {
        var warehouseId = $('#warehouseSelect').val();
        if (!warehouseId) {
            alert('请选择仓库！');
            return;
        }
        
        var startDate = $('#startDateInput').val();
        var endDate = $('#endDateInput').val();
        if (!startDate || !endDate) {
            alert('请选择查询时间范围！');
            return;
        }
        
        var startDateTime = startDate + ' 00:00:00';
        var endDateTime = endDate + ' 23:59:59';
        
        var storageArea = $('#storageAreaSelect').val();
        var deviceId = $('#deviceIdSelect').val();
        
        // 构建查询参数
        var params = {
            warehouseId: warehouseId,
            startTime: startDateTime,
            endTime: endDateTime
        };
        
        if (storageArea) {
            params.storageArea = storageArea;
        }
        
        if (deviceId) {
            params.deviceId = deviceId;
        }
        
        // 发送请求
        $.ajax({
            url: '/warehouse/coldStorageMonitor/history/data',
            type: 'GET',
            data: params,
            success: function(res) {
                if (res.code === 200) {
                    historyTable.clear().rows.add(res.data).draw();
                } else {
                    alert('查询失败：' + res.msg);
                }
            },
            error: function() {
                alert('查询失败，请稍后重试！');
            }
        });
    }
    
    // 格式化日期时间
    function formatDateTime(dateTime) {
        if (!dateTime) return '';
        
        var dt = new Date(dateTime);
        
        var year = dt.getFullYear();
        var month = padZero(dt.getMonth() + 1);
        var day = padZero(dt.getDate());
        var hour = padZero(dt.getHours());
        var minute = padZero(dt.getMinutes());
        var second = padZero(dt.getSeconds());
        
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    
    // 补零
    function padZero(num) {
        return num < 10 ? '0' + num : num;
    }
}); 